package com.example.shushiyunsst.fragment.main.wallet.sub

import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemChildClickListener
import com.example.library_common.adapter.JssBaseQuickAdapter
import com.example.library_common.adapter.JssBaseViewHolder
import com.example.library_common.base.SimpleListFragment
import com.example.library_common.bean.CommonBean
import com.example.library_common.utils.even.MessageWrap
import com.example.library_common.utils.even.TO_REFRESH_BALANCE_INFO
import com.example.library_common.utils.even.TO_REFRESH_BALANCE_INFO_Failed
import com.example.shushiyunsst.R
import com.example.shushiyunsst.fragment.getUserBalanceInfo
import com.example.shushiyunsst.fragment.main.home.child.miner22.CMLCollectionFragment
import com.example.shushiyunsst.fragment.main.home.child.miner22.CMLTransferFragment
import com.example.shushiyunsst.fragment.main.home.child.miner22.bean.CMLIntent
import com.example.shushiyunsst.fragment.main.wallet.bean.*
import com.example.wallet.bean.BalanceInfoBean
import com.example.wallet.bean.MyCaptureHeaderListBean
import com.example.wallet.db.BalanceInfoManager
import com.example.wallet.db.UserInfoManager
import com.example.wallet.global.AppGlobals
import ikidou.reflect.TypeBuilder
import java.lang.reflect.Type

/**
 * 资产
 * */
class MyCaptureFragment : SimpleListFragment<BalanceInfoBean.ListBean>(), WalletLabInfo,
    OnItemChildClickListener {


    override val title: Int = R.string.my_capture

    private val sst = AppGlobals.getApplication().getString(R.string.wallet_sst)

    private val cml = AppGlobals.getApplication().getString(R.string.wallet_cml)

    private val arl = AppGlobals.getApplication().getString(R.string.wallet_arl)

    private var headerListAdapter: JssBaseQuickAdapter<MyCaptureHeaderListBean>? = null

    companion object {

        fun newInstance(): MyCaptureFragment {
            val args = Bundle()
            val fragment = MyCaptureFragment()
            fragment.arguments = args
            return fragment
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        delayedTime = 0
        mSuperBackPressedSupport = false
        isAddDividerItemDecoration = false
        isEnableLoadMore = false
    }

    override fun initView(view: View) {
        view.setBackgroundColor(Color.TRANSPARENT)
        super.initView(view)

        val listHeaderLayout = LayoutInflater.from(_mActivity)
            .inflate(R.layout.my_capture_head_fragment_layout, view as ViewGroup, false)

        mAdapter.addHeaderView(listHeaderLayout)

        val headerRecyclerView: RecyclerView =
            listHeaderLayout.findViewById(R.id.headerRecyclerView)
        headerRecyclerView.setHasFixedSize(true)
        headerRecyclerView.layoutManager =
            LinearLayoutManager(_mActivity, LinearLayoutManager.HORIZONTAL, false)
        headerListAdapter = object :
            JssBaseQuickAdapter<MyCaptureHeaderListBean>(
                R.layout.my_capture_head_item_fragment_layout
            ) {
            override fun convert(holder: JssBaseViewHolder?, item: MyCaptureHeaderListBean?) {
                super.convert(holder, item)
                holder?.setText(R.id.title, item?.title.toString())
                    ?.setText(R.id.consumptionU, item?.consumptionU.toString())
                    ?.setText(R.id.marketPer, item?.marketPer.toString())
                    ?.setText(R.id.publicWelfareBalance, item?.publicWelfareBalance.toString())
                    ?.setText(R.id.destroyBalance, item?.destroyBalance.toString())
            }
        }
        headerRecyclerView.adapter = headerListAdapter

        mSwipeRefreshLayout.setColorScheme(R.color.nav_bar_bg_color)

        mSwipeRefreshLayout.setProgressBackgroundColor(R.color.colorAccent)

        mAdapter.addChildClickViewIds(
            R.id.transferTv, R.id.collectionsTv,
            R.id.rechargeTv, R.id.withdrawTv,
            R.id.detail, R.id.mExchangePass
        )

        mAdapter.setOnItemChildClickListener(this)

    }


    override fun getItemLayout() = R.layout.my_capture_fragment_item_layout

    override fun convertItem(helper: JssBaseViewHolder?, item: BalanceInfoBean.ListBean?) {

        var availableTvStr = ""

        var convertToCNYStr = ""

        if (item?.iswelfare == 1) {
            availableTvStr = "已释放： ${item.releasedStr}"
            convertToCNYStr = "未释放： ${item.notReleasedStr}"
        } else {
            availableTvStr = "可用: ${item?.balanceStr}"
            convertToCNYStr = "折合(CNY): ${item?.balanceCnyStr}"
        }

        val operationVisible =
            item?.isSupportTrans == 0
                    && item.isSupportTrans == 0
                    && item.isExchangePass == 0
                    && item.isSupportReceive == 0

        helper?.setText(R.id.moneyTv, item?.title)
            ?.setText(R.id.availableTv, availableTvStr)
            ?.setText(R.id.convertToCNY, convertToCNYStr)
            ?.setViewVisible(R.id.detail, item?.iswelfare == 1)
            ?.setViewVisible(R.id.transferFrameTv, item?.isSupportTrans == 1)
            ?.setViewVisible(R.id.mExchangeFramePass, item?.isExchangePass == 1)
            ?.setViewVisible(R.id.collectionsFrameTv, item?.isSupportReceive == 1)
            ?.setGone(R.id.operation, operationVisible)
    }

    override fun refreshData() {
        if (isLoaded) {
            delayedTime = 1000
            if (!mSwipeRefreshLayout.isRefreshing) {
                mSwipeRefreshLayout.isRefreshing = true
                onRefresh()
            }

        }
    }

    override fun getListType(): Type {
        return TypeBuilder.newInstance(CommonBean::class.java)
            .beginSubType(List::class.java)
            .addTypeParam(MyCaptureBean::class.java)
            .endSubType()
            .build()
    }

    override fun netRequest() {
//        loadData()
        getUserBalanceInfo(_mActivity)

    }

    override fun handMessage(msg: MessageWrap?) {
        super.handMessage(msg)
        when (msg?.message) {
            TO_REFRESH_BALANCE_INFO -> {
                loadData()
            }
            TO_REFRESH_BALANCE_INFO_Failed -> {
                onFailed()
            }
        }
//        if (msg?.message == TO_REFRESH_BALANCE_INFO) {
//
//        }
    }

    private fun loadData() {
        val balanceInfoBean = BalanceInfoManager.mBalanceInfoManager.getBalanceInfoBean()
        loadListDate(balanceInfoBean?.list)
        headerListAdapter?.clears()
        headerListAdapter?.data?.addAll(balanceInfoBean?.getcList()?: emptyList())

        delayedTime = 0
    }

    override fun onItemChildClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
        val item = mAdapter.getItem(position)

        when (view.id) {
            R.id.mExchangePass -> {
                start(PassCardExchangeFragment.newInstance(item))
            }
            R.id.detail -> {
                if (item.iswelfare == 1) {
                    start(WelfareFragment.newInstance())
                }
            }
            R.id.transferTv -> {
                //转账
                if (item.isExchangePass == 1) {
                    start(ExchangePassTransferFragment.newInstance(item))
                    return
                }
                transferHand(item)

            }
            R.id.collectionsTv -> {
                //收款
                if (item.isExchangePass == 1) {
                    start(CollectionsFragment.newInstance(item))
                    return
                }
                collectionsHand(item)
            }
            R.id.rechargeTv -> {
                //充币
                if (item.tokenType == sst) {
                    start(RechargeFragment.newInstance())
                }

            }
            R.id.withdrawTv -> {
                //提币
                if (item.tokenType == sst) {
                    start(WithdrawFragment.newInstance())
                }

            }
        }
    }

    //转账
    private fun transferHand(item: BalanceInfoBean.ListBean) {
        val userInfo = UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo
        val mAddress = userInfo?.sysWalletAddress ?: ""
        when (item.tokenType) {
            sst -> {
//                start(TransferFragment.newInstance())
                start(ExchangePassTransferFragment.newInstance(item))
            }
            cml, arl -> {
                val balance = "${item.balance}"


                val icon = item.tokenType

                val cmlIntent = CMLIntent(
                    mAddress,
                    balance,
                    icon,
                    icon,
                    CMLIntent.PARENT_ACCOUNT
                )
                cmlIntent.balanceCny = item.balanceCny.toString()
                start(CMLTransferFragment.newInstance(cmlIntent))
            }
        }
    }

    //收款
    private fun collectionsHand(item: BalanceInfoBean.ListBean) {
        val userInfo = UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo
        val mAddress = userInfo?.sysWalletAddress ?: ""
        when (item.tokenType) {
            sst -> {
                start(CollectionsFragment.newInstance())
            }
            cml, arl -> {
                val balance = "${item.balance}"

                val icon = item.tokenType
                val cmlIntent = CMLIntent(
                    mAddress,
                    balance,
                    icon,
                    icon,
                    CMLIntent.PARENT_ACCOUNT
                )
                cmlIntent.balanceCny = item.balanceCny.toString()
                start(CMLCollectionFragment.newInstance(cmlIntent))
            }

            else -> start(CollectionsFragment.newInstance())
        }

    }
}